package com.gitee.helioz.openai.api.endpoint.audio;

import com.gitee.helioz.openai.api.OpenAiService;
import com.gitee.helioz.openai.api.dto.audio.TranscriptionsRequest;
import com.gitee.helioz.openai.api.dto.audio.TranscriptionsResponse;
import com.gitee.helioz.openai.api.dto.audio.TranslationsRequest;
import com.gitee.helioz.openai.common.constants.OpenAiApiUrl;
import com.gitee.helioz.openai.common.util.BeanUtil;
import com.gitee.helioz.openai.common.util.http.HttpFilePart;
import com.gitee.helioz.openai.common.util.json.GsonUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 〈音频服务〉
 *
 * @author <a href="https://gitee.com/helioz">Morning Starr</a>
 */
@Slf4j
@RequiredArgsConstructor
public class AudioServiceImpl implements AudioService {

    private final OpenAiService openAiService;

    @Override
    public TranscriptionsResponse transcriptions(TranscriptionsRequest transRequest) {
        String requestJson = GsonUtil.toJson(transRequest);
        log.debug("将音频文件转录为文本，请求={}", requestJson);
        Map<String, Object> formMap = BeanUtil.beanToMap(transRequest, "file");
        List<HttpFilePart> fileParts = new ArrayList<>(3);
        HttpFilePart file = transRequest.getFile();
        if (file != null) {
            file.setPartName("file");
            fileParts.add(file);
        }
        String responseStr = openAiService.postFormData(OpenAiApiUrl.Audio.CREATE_TRANSCRIPTION.getUrl(openAiService.getApiHost()), formMap, fileParts);
        return GsonUtil.fromJson(responseStr, TranscriptionsResponse.class);
    }

    @Override
    public TranscriptionsResponse translations(TranslationsRequest transRequest) {
        String requestJson = GsonUtil.toJson(transRequest);
        log.debug("将音频翻译成英语，请求={}", requestJson);
        Map<String, Object> formMap = BeanUtil.beanToMap(transRequest, "file");
        List<HttpFilePart> fileParts = new ArrayList<>(3);
        HttpFilePart file = transRequest.getFile();
        if (file != null) {
            file.setPartName("file");
            fileParts.add(file);
        }
        String responseStr = openAiService.postFormData(OpenAiApiUrl.Audio.CREATE_TRANSLATION.getUrl(openAiService.getApiHost()), formMap, fileParts);
        return GsonUtil.fromJson(responseStr, TranscriptionsResponse.class);
    }
}
